package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.NcGasLog;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.INcGasLogService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 气值 信息操作处理
 *
 * @author ruoyi
 * @date 2019-07-31
 */
@Controller
@RequestMapping("/system/ncGasLog")
public class NcGasLogController extends BaseController {
    private String prefix = "system/ncGasLog";
    private String frontPrefix = "system/ncGasLog/front";

    @Autowired
    private INcGasLogService ncGasLogService;

    @RequiresPermissions("system:ncGasLog:view")
    @GetMapping()
    public String ncGasLog(ModelMap mmap) {
        return prefix + "/ncGasLog";
    }

    @GetMapping("/front")
    public String frontNcGasLog(String beginTime,String endTime,ModelMap mmap){
        ncGasLogService.showMag(beginTime,endTime,mmap);
        return frontPrefix + "/ncGasLog";
    }

    /**
     * 查询气值列表
     */
    @RequiresPermissions("system:ncGasLog:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(NcGasLog ncGasLog, ModelMap mmap) {
        startPage();

        List<NcGasLog> list = ncGasLogService.selectNcGasLogList(ncGasLog);


        Double gasTop = ncGasLogService.seleGasTop(ncGasLog); //拿到月区间的头一个值
        Double gasLow = ncGasLogService.seleGasLow(ncGasLog); //拿到月区间的末一个值


        Map m = new HashMap<>();
        m.put("gasTop",gasTop);
        m.put("gasLow",gasLow);

        TableDataInfo ti = getDataTable(list);
        ti.setParams(m);
        return ti;
    }


    /**
     * 导出气值列表
     */
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(NcGasLog ncGasLog) {
        List<NcGasLog> list = ncGasLogService.selectNcGasLogList(ncGasLog);
        ExcelUtil<NcGasLog> util = new ExcelUtil<NcGasLog>(NcGasLog.class);
        return util.exportExcel(list, "锅炉管理单");
    }

    /**
     * 新增气值
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存气值
     */
    @RequiresPermissions("system:ncGasLog:add")
    @Log(title = "气值", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(NcGasLog ncGasLog) {
        SysUser sysUser = ShiroUtils.getSysUser();
        ncGasLog.setCreateBy(sysUser.getLoginName()); //拿到登录的用户名

        Date nowdata = ncGasLog.getCreateTime();
        if (StringUtils.isNull(nowdata)) {
            ncGasLog.setCreateTime(new Date()); //系统当前时间
        }

        return toAjax(ncGasLogService.insertNcGasLog(ncGasLog));
    }

    /**
     * 修改气值
     */
    @GetMapping("/edit/{gasLogId}")
    public String edit(@PathVariable("gasLogId") Long gasLogId, ModelMap mmap) {
        NcGasLog ncGasLog = ncGasLogService.selectNcGasLogById(gasLogId);
        mmap.put("ncGasLog", ncGasLog);
        return prefix + "/edit";
    }

    /**
     * 修改保存气值
     */
    @RequiresPermissions("system:ncGasLog:edit")
    @Log(title = "气值", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(NcGasLog ncGasLog) {
        return toAjax(ncGasLogService.updateNcGasLog(ncGasLog));
    }

    /**
     * 删除气值
     */
    @RequiresPermissions("system:ncGasLog:remove")
    @Log(title = "气值", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(ncGasLogService.deleteNcGasLogByIds(ids));
    }


    /**
     * 锅炉气值
     */
    @GetMapping("/gasLog")
    public String gasLog(ModelMap mmap, String beginTime, String endTime, NcGasLog ncGasLog){
        if (StringUtils.isNotEmpty(beginTime)) {
            ncGasLog.getParams().put("beginTime", beginTime);
        }
        if (StringUtils.isNotEmpty(endTime)) {
            ncGasLog.getParams().put("endTime", endTime);
        }
        mmap.put("beginTime", beginTime);
        mmap.put("endTime", endTime);
        //总气值
        Double gasAmount= 0.0;
        Double log = ncGasLogService.selectGasAmount(ncGasLog);
        if (log !=null) {
            gasAmount =ncGasLogService.selectGasAmount(ncGasLog) ;
            mmap.put("gasAmount",gasAmount);
        }else {
            mmap.put("gasAmount",0);
        }

        //曲线图数据
        String[] last12Months = new String[12];
        Calendar cal = Calendar.getInstance();
        List zfeed=new ArrayList();
        List ffeed=new ArrayList();

        if (StringUtils.isNotEmpty(endTime)) {
            cal.setTime(DateUtils.dateTime("yyyy-MM-dd",endTime));
            //如果当前日期大于二月份的天数28天或者29天会导致计算月份错误，会多出一个三月份，故设置一个靠前日期解决此问题
            cal.set(Calendar.DAY_OF_MONTH, 1);
            for (int i = 0; i < 12; i++) {
                if(cal.get(Calendar.MONTH)+1<10){
                    last12Months[11 - i] = cal.get(Calendar.YEAR) + "-0" + (cal.get(Calendar.MONTH) + 1);
                }else{
                    last12Months[11 - i] = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1);
                }
                cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1); //逐次往前推1个月

            }
        }
        else if(StringUtils.isNotEmpty(beginTime)) {
            Calendar nowDateTime = Calendar.getInstance();
            if (beginTime.equals(nowDateTime.get(Calendar.YEAR) + "-01-01")) {
                cal.set(Calendar.DAY_OF_MONTH, 1);
                for (int i = 0; i < 12; i++) {
                    if (cal.get(Calendar.MONTH) + 1 < 10) {
                        last12Months[11 - i] = cal.get(Calendar.YEAR) + "-0" + (cal.get(Calendar.MONTH) + 1);
                    } else {
                        last12Months[11 - i] = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1);
                    }
                    cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1); //逐次往前推1个月

                }
            } else {
                cal.setTime(DateUtils.dateTime("yyyy-MM-dd", beginTime));
                int diffYear = nowDateTime.get(Calendar.YEAR) - cal.get(Calendar.YEAR);
                int diffMonth = diffYear * 12 + nowDateTime.get(Calendar.MONTH) - cal.get(Calendar.MONTH);
                if (diffMonth >= 12) {
                    //如果当前日期大于二月份的天数28天或者29天会导致计算月份错误，会多出一个三月份，故设置一个靠前日期解决此问题
                    nowDateTime.set(Calendar.DAY_OF_MONTH, 1);
                    for (int i = 0; i < 12; i++) {
                        if (nowDateTime.get(Calendar.MONTH) + 1 < 10) {
                            last12Months[11 - i] = nowDateTime.get(Calendar.YEAR) + "-0" + (nowDateTime.get(Calendar.MONTH) + 1);
                        } else {
                            last12Months[11 - i] = nowDateTime.get(Calendar.YEAR) + "-" + (nowDateTime.get(Calendar.MONTH) + 1);
                        }
                        nowDateTime.set(Calendar.MONTH, nowDateTime.get(Calendar.MONTH) - 1); //逐次往前推1个月

                    }
                } else {
                    //如果当前日期大于二月份的天数28天或者29天会导致计算月份错误，会多出一个三月份，故设置一个靠前日期解决此问题
                    cal.set(Calendar.DAY_OF_MONTH, 1);
                    for (int i = 0; i < 12; i++) {
                        if (cal.get(Calendar.MONTH) + 1 < 10) {
                            last12Months[11 - i] = cal.get(Calendar.YEAR) + "-0" + (cal.get(Calendar.MONTH) + 1);
                        } else {
                            last12Months[11 - i] = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1);
                        }
                        cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1); //逐次往前推1个月

                    }
                }

            }
        }
        else{
            //如果当前日期大于二月份的天数28天或者29天会导致计算月份错误，会多出一个三月份，故设置一个靠前日期解决此问题
            cal.set(Calendar.DAY_OF_MONTH, 1);
            for (int i = 0; i < 12; i++) {
                if(cal.get(Calendar.MONTH)+1<10){
                    last12Months[11 - i] = cal.get(Calendar.YEAR) + "-0" + (cal.get(Calendar.MONTH) + 1);
                }else{
                    last12Months[11 - i] = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1);
                }
                cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) - 1); //逐次往前推1个月

            }
        }



        for (int i = 0; i < last12Months.length; i++) {

            NcGasLog gasLog = new NcGasLog();
            gasLog.getParams().put("beginTime", last12Months[i]);

            //拿到一个月中的气值集合 如果当月只记录了一次 气值用量就等于这月用量减去上月最大用量
            List<NcGasLog> ncGasLogList = ncGasLogService.selectGasMonthList(gasLog);
            int sum =0;
            for (NcGasLog ncgaslog : ncGasLogList) {
                if (ncgaslog.getGasValue() !=null) {
                    sum ++;
                }
            }
            if(sum == 1){
                NcGasLog gasLogs = new NcGasLog();

//                String timeLow = ncGasLogService.seleTimeLow(gasLogs);
                try{
                    if(last12Months[i-1] !=null && !("").equals(last12Months[i-1])){ //没有上个月的话
                        gasLogs.getParams().put("beginTime", last12Months[i-1]);
                        Double ncGasLogMax = ncGasLogService.selectGasMonth(gasLogs);
                        for (NcGasLog ncgaslog : ncGasLogList) {
                            if(ncGasLogMax!=null){
                                /*new DecimalFormat("0.00").format(Double.valueOf(ncFeedLogService.selectNcFeedLogMonthAmountCows(feed)))*/
                                zfeed.add(new DecimalFormat("0.00").format(ncgaslog.getGasValue().doubleValue() - ncGasLogMax));
                            }else {
                                zfeed.add(new DecimalFormat("0.00").format(ncgaslog.getGasValue().doubleValue()));
                            }
                        }
                    }
                }catch (Exception e){
                    for (NcGasLog ncgaslog : ncGasLogList) {
                        //没有上个月就证明是第一个月，气表是多少就证明是多少
                        zfeed.add(new DecimalFormat("0.00").format(ncgaslog.getGasValue().doubleValue()));
                    }
                }
            }else {
                //从一个月中获取到所有的 用最大的值减去最小的值 得到的就是本月的用气值
                Double ncGasLogMax = ncGasLogService.selectGasMonth(gasLog);

                Double ncgasListMin = ncGasLogService.selectGasMonthMin(gasLog);

                if(ncgasListMin!=null && ncGasLogMax !=null){
                    /*Math.abs()*/
                    zfeed.add(new DecimalFormat("0.00").format(ncGasLogMax - ncgasListMin));
                }else{
                    zfeed.add("0.00");
                }
            }



        }




        mmap.put("zfeed",zfeed);
        mmap.put("ffeed",ffeed);
        mmap.put("dataTime",last12Months);
        return frontPrefix + "/ncGasLog";
    }


    private String prefix_screen = "system/screen";
    //大屏锅炉房2
    @GetMapping("/GasLogScreen")
    public String gaslogScreen(ModelMap map){
        Calendar cal=Calendar.getInstance();
        //获取最近8天的数据
        List<Double> gasAmount=new ArrayList<Double>();
      NcGasLog gasLog=new NcGasLog();
        NcGasLog gasLog1=new NcGasLog();
        String[] last7Day=last7Day(cal,8);
        for(int i=0;i<7;i++) {
            gasLog.getParams().put("day",last7Day[i]);
            gasLog1.getParams().put("day",last7Day[i+1]);
            double amount=ncGasLogService.seleGasLowScreen(gasLog);
            double amount1=ncGasLogService.seleGasLowScreen(gasLog1);
            gasAmount.add(amount1-amount);
        }
        String[] date=last7Day(cal,7);
        map.put("gasAmount", gasAmount);
        map.put("date", date);
        map.put("user", ShiroUtils.getSysUser());


        //今天以及昨天同比
        NcGasLog gasLog2=new NcGasLog();
        Calendar   cal1=Calendar.getInstance();
        SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
        String time2 = format2.format(Calendar.getInstance().getTime());
        gasLog2.getParams().put("day",time2);
        double todayAmount=ncGasLogService.seleGasLowScreen(gasLog2);

        cal1.add(Calendar.DATE,   -1);
        String yesterday =format2.format(cal1.getTime());
        gasLog2.getParams().put("day",yesterday);
        double todayAmount1=ncGasLogService.seleGasLowScreen(gasLog2);
        //保存今天的值
        if (todayAmount == 0){
            map.put("today", todayAmount);
        }else{

        map.put("today", todayAmount-todayAmount1);
        }
        //昨天的值
        cal1.add(Calendar.DATE,   -1);
        String yesterday1 =format2.format(cal1.getTime());
        gasLog2.getParams().put("day",yesterday1);
       double yestAmount=todayAmount1-ncGasLogService.seleGasLowScreen(gasLog2);

        if(yestAmount != 0){
            map.put("dayRatio", new DecimalFormat("0.00").format(Double.valueOf(((todayAmount-todayAmount1)- yestAmount) /  yestAmount * 100)));
        }
        else{
            map.put("dayRatio", new DecimalFormat("0.00").format(Double.valueOf(todayAmount-todayAmount1)));
        }
        //本月以及上个月同比
        NcGasLog gasLog3=new NcGasLog();
        Calendar  cal2=Calendar.getInstance();
        String month=null;
        if (cal2.get(Calendar.MONTH) + 1 < 10) {
            month= cal2.get(Calendar.YEAR) + "-0" + (cal2.get(Calendar.MONTH) + 1);
        }
        else {
            month = cal2.get(Calendar.YEAR) + "-" + (cal2.get(Calendar.MONTH) + 1);
        }
        gasLog3.getParams().put("month",month);
        double monthAmount=ncGasLogService.seleGasLowScreen(gasLog3);
        //上个月
        String lastMonth=null;
        cal2.add(Calendar.MONTH,-1);
        if (cal2.get(Calendar.MONTH) + 1 < 10) {
            lastMonth= cal2.get(Calendar.YEAR) + "-0" + (cal2.get(Calendar.MONTH) + 1);
        }
        else {
            lastMonth = cal2.get(Calendar.YEAR) + "-" + (cal2.get(Calendar.MONTH) + 1);
        }

        gasLog3.getParams().put("month",lastMonth);
        double laMonth=ncGasLogService.seleGasLowScreen(gasLog3);
        //上上个月
        String lastMonth1=null;
        cal2.add(Calendar.MONTH,-1);
        if (cal2.get(Calendar.MONTH) + 1 < 10) {
            lastMonth1= cal2.get(Calendar.YEAR) + "-0" + (cal2.get(Calendar.MONTH) + 1);
        }
        else {
            lastMonth1 = cal2.get(Calendar.YEAR) + "-" + (cal2.get(Calendar.MONTH) + 1);
        }
        //本月与上月对比

        gasLog3.getParams().put("month",lastMonth1);
        double laMonth1=ncGasLogService.seleGasLowScreen(gasLog3);
        map.put("month", monthAmount-laMonth);
        double s1=laMonth-laMonth1;
        if((laMonth-laMonth1) != 0){
            map.put("monthRatio", new DecimalFormat("0.00").format(Double.valueOf(((monthAmount-laMonth)- s1) / s1 * 100)));
        }
        else{
            map.put("monthRatio", new DecimalFormat("0.00").format(Double.valueOf(monthAmount-laMonth)));
        }
        //本年以及去年月同比
        NcGasLog gasLog4=new NcGasLog();
        Calendar   cal3=Calendar.getInstance();
        String year=cal3.get(Calendar.YEAR)+"";
        gasLog4.getParams().put("year",year);
        double thisYear=ncGasLogService.seleGasLowScreen(gasLog4);

        cal3.add(Calendar.YEAR,-1);
        String year1 = cal3.get(Calendar.YEAR) + "";
        gasLog4.getParams().put("year",year1);
        double lastYear=ncGasLogService.seleGasLowScreen(gasLog4);

        cal3.add(Calendar.YEAR,-1);
        String year2 = cal3.get(Calendar.YEAR) + "";
        gasLog4.getParams().put("year",year2);
        double lastYear2=ncGasLogService.seleGasLowScreen(gasLog4);
       double s=lastYear-lastYear2;
        map.put("year", thisYear-lastYear);
        if((lastYear-lastYear2) != 0){
            map.put("yearRatio", new DecimalFormat("0.00").format(Double.valueOf(((thisYear-lastYear)-(lastYear-lastYear2))/s * 100)));
        }
        else{
            map.put("yearRatio", new DecimalFormat("0.00").format(Double.valueOf(thisYear-lastYear)));
        }
        return prefix_screen + "/guolu-2";
    }
    //产生最近的时间
    public String[] last7Day(Calendar cal,int sum) {
        String[] last7Day = new String[sum];
        for (int i = 0; i < sum; i++) {
            if (cal.get(Calendar.MONTH) + 1 < 10) {
                if (cal.get(Calendar.DATE) < 10) {
                    last7Day[(sum-1) - i] = cal.get(Calendar.YEAR) + "-0" + (cal.get(Calendar.MONTH) + 1) + "-0" + (cal.get(Calendar.DATE));
                } else {
                    last7Day[(sum-1) - i] = cal.get(Calendar.YEAR) + "-0" + (cal.get(Calendar.MONTH) + 1) + "-" + (cal.get(Calendar.DATE));
                }
            } else {
                if (cal.get(Calendar.DATE) < 10) {
                    last7Day[(sum-1) - i] = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-0" + (cal.get(Calendar.DATE));
                } else {
                    last7Day[(sum-1) - i] = cal.get(Calendar.YEAR) + "-" + (cal.get(Calendar.MONTH) + 1) + "-" + (cal.get(Calendar.DATE));
                }

            }
            cal.set(Calendar.DATE, cal.get(Calendar.DATE) - 1); //逐次往前推1天*/

        }
        return last7Day;
    }

}
